package seatiger.tomcat.coyote.http11;

import seatiger.tomcat.coyote.ActionCode;
import seatiger.tomcat.coyote.ActionHook;
import seatiger.tomcat.coyote.Adapter;
import seatiger.tomcat.coyote.ProtocolHandler;
import seatiger.tomcat.util.net.NioChannel;
import seatiger.tomcat.util.net.NioEndpoint;

import java.util.concurrent.Executor;

/**
 * nio的协议处理类
 */
public class Http11NioProtocol implements ProtocolHandler {

    private Adapter adapter;
    private Http11ConnectionHandler cHandler;

    protected NioEndpoint ep = new NioEndpoint();

    public Http11NioProtocol() {
        cHandler = new Http11ConnectionHandler(this);
    }

    @Override
    public void init() throws Exception {
        ep.setHandler(cHandler);
        ep.init();
    }

    @Override
    public void start() throws Exception {
        ep.start();
    }

    @Override
    public void setPort(int port) {
        ep.setPort(port);
    }

    @Override
    public void setExecutor(Executor executor) {
        ep.setExecutor(executor);
    }


    @Override
    public void destroy() throws Exception {

    }

    @Override
    public void setAdapter(Adapter adapter) {
        this.adapter = adapter;
    }


    public static class Http11ConnectionHandler implements NioEndpoint.NioChannelHandler {
        protected Http11NioProtocol proto;
        public Http11ConnectionHandler(Http11NioProtocol proto) {
            this.proto = proto;
        }

        @Override
        public void process(NioChannel nioChannel) {
            Http11NioProcessor processor = new Http11NioProcessor(8 * 1024);
            processor.setAdapter(proto.adapter);
            try {
                if (processor instanceof ActionHook) {
                    ((ActionHook) processor).action(ActionCode.ACTION_START, null);
                }
                processor.process(nioChannel);

            }catch (Exception e) {
            }
        }
    }
}
